<?php

if (!function_exists('os_db_input')){
function os_db_input($string, $link = 'db_link') 
{
  global $$link;

  if (function_exists('mysql_real_escape_string')) 
  {
      return mysql_real_escape_string($string, $$link);
  } 
  elseif (function_exists('mysql_escape_string')) 
  {
      return mysql_escape_string($string);
  }

  return addslashes($string);
}
}

if (!function_exists('os_db_prepare_input')){
function os_db_prepare_input($string) 
{
    if (is_string($string)) 
	{
        return trim(stripslashes($string));
    } 
	elseif (is_array($string)) 
	{
        reset($string);
        while (list($key, $value) = each($string)) 
		{
             $string[$key] = os_db_prepare_input($value);
        }
        return $string;
    } 
	else 
	{
        return $string;
    }
}
}

function os_db_num_rows($db_query,$cq=false) 
{
    if (DB_CACHE=='true' && $cq) 
	{
       if (!count($db_query)) return false;
       return count($db_query);
    } 
	else 
	{
       if (!is_array($db_query)) return mysql_num_rows($db_query);
    }
}

function os_db_fetch_array(&$db_query, $cq=false) 
{
    if (DB_CACHE=='true' && $cq) 
	{
        if (!count($db_query)) return false;
        if (is_array($db_query)) {
        $curr = current($db_query);
        next($db_query);
        }
        return $curr;
    } 
	else 
	{
        if (is_array($db_query)) 
		{
           $curr = current($db_query);
           next($db_query);
           return $curr;
        }
		if (empty($db_query)) return false;
        return @mysql_fetch_array($db_query, MYSQL_ASSOC);
    }
}

function os_db_test_connection($database) 
{
    global $db_error;

    $db_error = false;

    if (!$db_error) 
	{
        if (!@os_db_select_db($database)) 
		{
            $db_error = mysql_error();
        } 
		else 
		{
           if (!@os_db_query_installer("select count(*) from " . TABLE_CONFIGURATION . "")) 
		   {
              $db_error = mysql_error();
           }
        }
    }

    if ($db_error) 
	{
        return false;
    } 
	else 
	{
        return true;
    }
}
    
function os_db_connect($server = DB_SERVER, $username = DB_SERVER_USERNAME, $password = DB_SERVER_PASSWORD, $database = DB_DATABASE, $link = 'db_link', $use_pconnect = USE_PCONNECT, $new_link = false) 
{
    global $$link;

    if ($use_pconnect == 'true') 
	{
        $$link = mysql_pconnect($server, $username, $password);
    } 
	else 
	{
        $$link = @mysql_connect($server, $username, $password, $new_link);
    }

    if ($$link)
	{
        @mysql_select_db($database);
        @mysql_query("SET SQL_MODE= ''");
        @mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
    }

    if (!$$link) 
	{
        os_db_error("connect", mysql_errno(), mysql_error());
    }

    return $$link;
}

$db_query = array();

function os_db_queryCached($query, $link = 'db_link') {
    global $$link;

    // get HASH ID for filename
    $id=md5($query);


    // cache File Name
    $file=SQL_CACHEDIR.$id.'.os';

    // file life time
    $expire = DB_CACHE_EXPIRE; // 24 hours

    if (STORE_DB_TRANSACTIONS == 'true') {
      error_log('QUERY ' . $query . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
    }

    if (file_exists($file) && filemtime($file) > (time() - $expire)) {

     // get cached resulst
        $result = unserialize(implode('',file($file)));

        } else {

         if (file_exists($file)) @unlink($file);

        // get result from DB and create new file
        $result = mysql_query($query, $$link) or os_db_error($query, mysql_errno(), mysql_error());

        if (STORE_DB_TRANSACTIONS == 'true') {
                $result_error = mysql_error();
                error_log('RESULT ' . $result . ' ' . $result_error . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
        }

        // fetch data into array
        while ($record = os_db_fetch_array($result))
                $records[]=$record;


        // safe result into file.
        $stream = serialize($records);
        $fp = fopen($file,"w");
        fwrite($fp, $stream);
        fclose($fp);
        $result = $records;

   }

    return $result;
}
  
function os_db_query($query, $link = 'db_link') 
{
    global $db_query;
    global $$link;
    global $query_counts;
    $query_counts++; 

    //echo $query.'<br>';

    if (STORE_DB_TRANSACTIONS == 'true') {
      error_log('QUERY ' . $query . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
    }
	  
    $result = mysql_query($query, $$link) or os_db_error($query, mysql_errno(), mysql_error());

    if (STORE_DB_TRANSACTIONS == 'true') {
       $result_error = mysql_error();
       error_log('RESULT ' . $result . ' ' . $result_error . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
    }

    if (!$result) {
      os_db_error($query, mysql_errno(), mysql_error());
    }

    if (DISPLAY_DB_QUERY == 'true')
	{
	    $db_text = $query;
        $db_text = str_replace("\r\n", "", $db_text); 
        $db_text = str_replace("\n","",$db_text);
		$db_text = strtolower($db_text);
        $db_text = trim($db_text);
        $db_text = preg_replace("|[\s]+|s", " ", $db_text);
		
	    //$db_query[$query_counts] = $db_text;
		
		if (isset($db_query[$db_text]))
        {
		   $db_query[$db_text]++;
		}	
        else
        {
		   $db_query[$db_text] = 1;
		}		
    }
	
    return $result;
}
   
 function os_db_perform($table, $data, $action = 'insert', $parameters = '', $link = 'db_link') 
 {
    reset($data);

    if ($action == 'insert') {
      $query = 'insert into ' . $table . ' (';
      while (list($columns, ) = each($data)) {
        $query .= $columns . ', ';
      }
      $query = substr($query, 0, -2) . ') values (';
      reset($data);
      while (list(, $value) = each($data)) {
      	 $value = (is_Float($value) & PHP4_3_10) ? sprintf("%.F",$value) : (string)($value);
        switch ($value) {
          case 'now()':
            $query .= 'now(), ';
            break;
          case 'null':
            $query .= 'null, ';
            break;
          default:
            $query .= '\'' . os_db_input($value) . '\', ';
            break;
        }
      }
      $query = substr($query, 0, -2) . ')';
    } elseif ($action == 'update') {
      $query = 'update ' . $table . ' set ';
      while (list($columns, $value) = each($data)) {
         $value = (is_Float($value) & PHP4_3_10) ? sprintf("%.F",$value) : (string)($value);
      	switch ($value) {
          case 'now()':
            $query .= $columns . ' = now(), ';
            break;
          case 'null':
            $query .= $columns .= ' = null, ';
            break;
          default:
            $query .= $columns . ' = \'' . os_db_input($value) . '\', ';
            break;
        }
      }
      $query = substr($query, 0, -2) . ' where ' . $parameters;
    }

    return os_db_query($query, $link);
}
  
 
function os_db_error($query, $errno, $error) 
{
    global $db;
	$db->error($query, $errno, $error);
} 

function osDBquery($query) {
	if (DB_CACHE == 'true') {
		$result = os_db_queryCached($query);
	} else {
		$result = os_db_query($query);

	}
	return $result;
}

function shopos_trace_back($backtrace=false, $from=0, $to=0, $get_call=true)
{
	if (!$backtrace) $backtrace = debug_backtrace();
	$output = array();
	for ($i=count($backtrace)-1-$from;$i>$to-1;$i--) 
	{
		$args = '';
		if ($get_call && is_array($backtrace[$i]['args']))
		{
			$args = str_replace("\n", "; ", shopos_trace_vardump($backtrace[$i]['args']));
		}
		$output[] = $backtrace[$i]['file'].":".$backtrace[$i]['line'] . (($get_call) ? "(".$backtrace[$i]['class'].$backtrace[$i]['type'].$backtrace[$i]['function'].$args.")" : "");
	}
	return $output;
}

function shopos_trace_vardump($var)
{
	ob_start();
	var_dump($var);
	$out = ob_get_contents();
	ob_end_clean();
	return($out);
}  

function os_db_insert_id() 
{
    return mysql_insert_id();
}

function os_db_output($string) 
{
    return htmlspecialchars($string);
}


function os_db_select_db($database) 
{
    return mysql_select_db($database);
}

function os_db_fetch_fields($db_query) 
{
    return mysql_fetch_field($db_query);
}
  
function os_db_close($link = 'db_link') 
{
    global $$link;
    return mysql_close($$link);
}	 
 
function os_db_free_result(&$db_query) 
{
    if (is_array($db_query)) 
	{
        unset($db_query);
        return true;
    } 
	else 
	{
        return mysql_free_result($db_query);
    }
}

function os_db_data_seek($db_query, $row_number,$cq=false) 
{
    if (DB_CACHE=='true' && $cq) {
    if (!count($db_query)) return;
     return $db_query[$row_number];
      } else {

         if (!is_array($db_query)) return mysql_data_seek($db_query, $row_number);

      }
}
 
function os_sqlSafeString($param) 
{
    global $$link;
    // Hier wird wg. der grossen Verbreitung auf MySQL eingegangen
	if (function_exists('mysql_real_escape_string')) 
    {
        $_param = mysql_real_escape_string($param, $$link);
    } 
    elseif (function_exists('mysql_escape_string')) 
    {
        $_param = mysql_escape_string($param);
    }
	
    return (NULL === $param ? "NULL" : '"' . $_param . '"');
} 
?>